<template>
	<jk-dialog
		:dialog-state="showDialog"
		:title="`${formData.machineName || '机台'}-工艺`"
		width="1100px"
		append-to-body
		:show-close-btn="disabled"
		:show-confirm-btn="pageType !== 'detail' && !disabled"
		:show-cancel-btn="pageType !== 'detail' && !disabled"
		@on-cancel="onVisibleChange(false)"
		@on-close="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
		@on-visible-change="onVisibleChange"
	>
		<el-form ref="ruleForm" :model="ruleForm" :hide-required-asterisk="pageType === 'detail'" :rules="rules" label-width="120px" :show-message="false">
			<div ref="box1">
				<el-tag type="primary" effect="plain" class="margin-bottom-10">
					<span class="el-icon-paperclip item-gap"></span>
					<span>工艺信息</span>
				</el-tag>
				<el-row>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="品种工艺单">
							<span v-if="pageType === 'detail' || disabled" class="read-only-2">{{ ruleForm.code }}</span>
							<remote-search-technology-order-input
								v-else
								placeholder="用户工艺编号"
								only-key="id"
								query-name="code"
								:form-data="ruleForm"
								@on-select="onSelectTechnologyOrderChange"
							></remote-search-technology-order-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="台日单产" prop="dailyYield1">
							<span v-if="pageType === 'detail' || disabled || ruleForm.code" class="read-only-2">{{ ruleForm.dailyYield }}</span>
							<jk-number-input v-else v-model="ruleForm.dailyYield" placeholder="台日单产" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="公定回潮率%">
							<span v-if="pageType === 'detail' || disabled || ruleForm.code" class="read-only-2">{{ ruleForm.moistureRegain }}</span>
							<jk-number-input v-else v-model="ruleForm.moistureRegain" placeholder="公定回潮率%" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="运转效率%">
							<span v-if="pageType === 'detail' || disabled || ruleForm.code" class="read-only-2">{{ ruleForm.efficiencyPercent }}</span>
							<jk-number-input v-else v-model="ruleForm.efficiencyPercent" :max="100" placeholder="运转效率%" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="定量(g/m)" prop="gramWeight">
							<div class="flex-start">
								<span v-if="pageType === 'detail' || disabled || ruleForm.code" class="read-only-2">{{ ruleForm.gramWeight }}</span>
								<jk-number-input v-else v-model="ruleForm.gramWeight" :disabled="!!ruleForm.specSheetId" style="width: 100%;" placeholder="克重" />
								<span>~</span>
								<span v-if="pageType === 'detail' || disabled || ruleForm.code" class="read-only-2">{{ ruleForm.meters }}</span>
								<jk-number-input v-else v-model="ruleForm.meters" :disabled="!!ruleForm.specSheetId" style="width: 100%;" placeholder="米长" />
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</div>
			<div class="margin-bottom-10">
				<el-tag ref="box2" type="primary" effect="plain">
					<span class="el-icon-notebook-2 item-gap"></span>
					<span>工艺项目</span>
				</el-tag>
			</div>
			<jk-table ref="jkTable" :data="ruleForm.specSheetParamList" border :height="dialogTableHeight - 30" style="width: 100%">
				<vxe-column :visible="pageType !== 'detail' && !disabled" title="操作" align="center" field="operation" :width="80">
					<template slot="header">
						<el-button size="mini" type="text" @click="onAddBtn">+添加</el-button>
					</template>
					<template slot-scope="scope">
						<div class="flex-center">
							<el-button size="mini" fixed="left" type="text" :disabled="!!ruleForm.code" @click="onRemoveBtn(scope)"><span class="el-icon-delete"></span></el-button>
						</div>
					</template>
				</vxe-column>
				<vxe-table-column type="seq" title="序号" :width="60" align="center" />
				<vxe-table-column field="specParamName" title="工艺项目" :min-width="120">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || processCode.toUpperCase() === 'CS' || disabled || ruleForm.code">{{ scope.row.specParamName }}</span>
						<div v-else>
							<el-select v-model="scope.row.specParamId" size="mini" clearable placeholder="工艺项目" class="width-100-percent" @change="onItemChange($event, scope)">
								<el-option
									v-for="item in itemList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								></el-option>
							</el-select>
						</div>
					</template>
				</vxe-table-column>
				<vxe-table-column field="valMin" title="下限值" align="right" :width="120">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || disabled || ruleForm.code">{{ scope.row.valMin }}</span>
						<div v-else>
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMin" size="mini"></jk-number-input>
							<jk-input v-else v-model="scope.row.valMin" size="mini" placeholder=""></jk-input>
						</div>
					</template>
				</vxe-table-column>
				<vxe-table-column field="val" title="标准值" align="right" :width="120">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || disabled || ruleForm.code">{{ scope.row.valMin }}</span>
						<div v-else>
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.val" size="mini"></jk-number-input>
							<jk-input v-else v-model="scope.row.val" size="mini" placeholder=""></jk-input>
						</div>
					</template>
				</vxe-table-column>
				<vxe-table-column field="valMax" title="上限值" align="right" :width="120">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.code">{{ scope.row.valMin }}</span>
						<div v-else>
							<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMax" size="mini"></jk-number-input>
							<jk-input v-else v-model="scope.row.valMax" size="mini" placeholder=""></jk-input>
						</div>
					</template>
				</vxe-table-column>
				<vxe-table-column field="paramType" title="项目类型" :width="100" align="center">
					<template slot-scope="scope">
						{{ scope.row.paramsType === 1 ? '设备工艺' : '运转工艺' }}
					</template>
				</vxe-table-column>
				<vxe-table-column field="ifNull" title="是否为空" :width="90" align="center">
					<template slot-scope="scope">
						{{ scope.row.ifNull ? '是' : '否' }}
					</template>
				</vxe-table-column>
				<vxe-table-column field="ifBusi" title="是否翻改项目" :width="100" align="center">
					<template slot-scope="scope">
						{{ scope.row.ifBusi ? '是' : '否' }}
					</template>
				</vxe-table-column>
				<vxe-table-column field="dataType" title="数据类型" :width="90" align="center">
					<template slot-scope="scope">
						{{ scope.row.dataType === 1 ? '数字' : '字符' }}
					</template>
				</vxe-table-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '../../../../mixins/cal-dialog-height';
    import { spinSpecSheetGet } from '../../../../api/technology/order';
    import remoteSearchTechnologyOrderInput from '../../order/components/remote-search-technology-order-input';
    export default {
        components: { remoteSearchTechnologyOrderInput },
        mixins: [calHeight],
        props: {
            disabled: {
                type: Boolean,
                default: false
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            processCode: {
                type: String,
                default: ''
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        data() {
            const validateGm = (rules, value, callback) => {
                if (value && this.ruleForm.gramWeight && this.ruleForm.meters) {
                    return callback();
                } else {
                    return callback(new Error());
                }
            };
            return {
                itemList: [],
                ruleForm: {
                    'code': '',
                    'batchCode': '',
                    'dailyYield': null,
                    'efficiencyPercent': null,
                    'fixedLength': null,
                    'gramWeight': null,
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'meters': null,
                    'moistureRegain': null,
                    'numbers': null,
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'productCode': '',
                    'productId': null,
                    'productModels': '',
                    'productName': '',
                    'specDate': '',
                    'specEmpId': null,
                    'specEmpName': ''
                },
                rules: {
                    moistureRegain: [{ required: true, trigger: 'change' }],
                    gramWeight: [{ required: true, validator: validateGm, trigger: 'change' }],
                    fixedLength: [{ required: true, trigger: 'change' }],
                    efficiencyPercent: [{ required: true, trigger: 'change' }],
                    dailyYield: [{ required: true, trigger: 'change' }],
                    specEmpId: [{ required: true, trigger: 'change' }],
                    productId: [{ required: true, trigger: 'change' }],
                    machineModelId: [{ required: true, trigger: 'change' }],
                    batchCode: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                },
                tableData: [],
                showDialog: false
            };
        },
        methods: {
            onItemChange(e, scope) {
                let item = {};
                if (e) {
                    item = this.itemList.find(k => k.id === e);
                } else {
                    item = {
                        specParamId: null,
                        specParamCode: '',
                        specParamName: '',
                        valMax: null,
                        valMin: null,
                        paramsType: null,
                        ifNull: null,
                        dataType: null
                    };
                }
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'specParamCode', item.code);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'specParamName', item.name);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMax', item.valMax);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMin', item.valMin);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'paramsType', item.paramsType);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'ifNull', item.ifNull);
                this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'dataType', item.dataType);
            },
            onRemoveBtn(scope) {
                this.ruleForm.specSheetParamList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                if (!this.ruleForm.code) {
                    if (!this.ruleForm.specSheetParamList) {
                        this.ruleForm.specSheetParamList = [];
                    }
                    this.ruleForm.specSheetParamList.push(this.defaultRowData());
                }
            },
            defaultRowData() {
                return {
                    name: '',
                    value: ''
                };
            },
            onSelectTechnologyOrderChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'id', e.id);
                    this.$set(this.ruleForm, 'code', e.code);
                    this.getTechnologyOrderDetailRequest(e.id);
                } else {
                    this.$set(this.ruleForm, 'id', null);
                    this.$set(this.ruleForm, 'code', '');
                    this.$set(this.ruleForm, 'machineModelCode', '');
                    this.$set(this.ruleForm, 'machineModelName', '');
                    this.$set(this.ruleForm, 'dailyYield', null);
                    this.$set(this.ruleForm, 'moistureRegain', null);
                    this.$set(this.ruleForm, 'efficiencyPercent', null);
                    this.$set(this.ruleForm, 'gramWeight', null);
                    this.$set(this.ruleForm, 'meters', null);
                    this.$set(this.ruleForm, 'specSheetParamList', []);
                }
            },
            getTechnologyOrderDetailRequest(id) {
                spinSpecSheetGet({ id }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        this.ruleForm.specSheetParamList.map(x => {
                            x.val = x.dataType === 1 ? Number(x.val) : x.val;
                            x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
                            x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
                            return x;
                        });
                        this.$set(this.ruleForm, 'id', res.data.res.id);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.$refs['ruleForm'].validate(valid => {
                            if (valid) {
                                const cpData = JSON.parse(JSON.stringify(this.ruleForm));
                                this.$emit('on-confirm', JSON.parse(JSON.stringify(cpData)));
                            } else {
                                this.$tipsBar(this, 'validator');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
            },
            getItemListRequest() {
                /* return spinSpecParamPage({ processCode: this.processCode }).then(res => {
                    if (res.data.status === 200) {
                        this.itemList = res.data.res;
                    }
                });*/
            },
            getDetailRequest() {
                return spinSpecSheetGet({ id: this.formData.specSheetId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                if (!this.formData.specSheetId) {
                    this.ruleForm = JSON.parse(JSON.stringify(this.formData));
                    await this.getItemListRequest();
                } else {
                    await this.getDetailRequest();
                }
                this.tableLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
